﻿/**********************************************
*公共工具类      
*create By: 陈斌          
*create Time:06/01/2012 17:25:05              
**********************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.Xml;
using System.Collections;
using System.IO;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Web;
using System.Reflection;

using NPOI;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;


namespace CommonLib
{
    public class GeneralTools
    {

    
        //MD5字符串加密
        public static string MD5Encrpyt(String SourceStr)
        {
            System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();            
            byte[] Bstr = System.Text.Encoding.UTF8.GetBytes(SourceStr);
            Bstr = x.ComputeHash(Bstr);
            StringBuilder ResStr = new StringBuilder();
            foreach (byte b in Bstr)
            {
                ResStr.Append(b.ToString("x2").ToLower());
            }
            return ResStr.ToString();
        }
        /// <summary>
        /// 随机生成编码
        /// </summary>
        /// <param name="length">编码长度</param>
        /// <returns>生成的编码</returns>
        public static string GetRandomCode(int length)
        {
            byte[] random = new Byte[length];
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            rng.GetNonZeroBytes(random);
            Random rnd = new Random();

            //StringBuilder sb = new StringBuilder(length);
            //int i;
            //for (i = 0; i < random.Length; i++)
            //{
            //    sb.Append(String.Format("{0:X2}", random[i]));
            //}
            return rnd.Next(0, 99999999).ToString("00000000");
        }
        /// <summary>
        /// 生成模拟纸质票号
        /// </summary>
        /// <returns></returns>
        public static string GetSimTicketNo()
        {
            byte[] random = new Byte[4];
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            rng.GetNonZeroBytes(random);
            StringBuilder sb = new StringBuilder();
            Random rnd = new Random();
            int i;
            for (i = 0; i < 4; i++)
            {            
                rnd.Next(0, 9999).ToString("0000");
                sb.Append(rnd.Next(0, 9999).ToString("0000") + "-");
            }
            return sb.ToString().Remove(sb.Length - 1);
        }
        /// <summary>
        /// DateTime时间格式转换为Unix时间戳格式
        /// </summary>
        /// <param name="time"> DateTime时间格式</param>
        /// <returns>Unix时间戳格式</returns>
        public static int ConvertDateTimeInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }
        /// <summary>  
        /// 将c# DateTime时间格式转换为Unix时间戳格式  
        /// </summary>  
        /// <param name="time">时间</param>  
        /// <returns>long</returns>  
        public static long ConvertDateTimeInt13(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
            long t = (time.Ticks - startTime.Ticks) / 10000;   //除10000调整为13位      
            return t;
        }

        //INI文件名  
        [DllImport("kernel32")]//返回0表示失败，非0为成功
        private static extern long WritePrivateProfileString(string section, string key,
             string val, string filePath);

        [DllImport("kernel32")]//返回取得字符串缓冲区的长度
        private static extern long GetPrivateProfileString(string section, string key,
            string def, StringBuilder retVal, int size, string filePath);


        public static string ReadIniData(string Section, string Key, string NoText, string iniFilePath)
        {
            if (File.Exists(iniFilePath))
            {
                StringBuilder temp = new StringBuilder(1024);
                GetPrivateProfileString(Section, Key, NoText, temp, 1024, iniFilePath);
                return temp.ToString();
            }
            else
            {
                return String.Empty;
            }
        }

        public static bool WriteIniData(string Section, string Key, string Value, string iniFilePath)
        {
            if (File.Exists(iniFilePath))
            {
                long OpStation = WritePrivateProfileString(Section, Key, Value, iniFilePath);
                if (OpStation == 0)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            else
            {
                try
                {

                    // Create the file.
                    using (FileStream fs = File.Create(iniFilePath))
                    {
                        Byte[] info = new UTF8Encoding(true).GetBytes("");
                        // Add some information to the file.
                        fs.Write(info, 0, info.Length);
                    }
                    long OpStation = WritePrivateProfileString(Section, Key, Value, iniFilePath);
                    if (OpStation == 0)
                    {
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
                catch (Exception ex)
                {
                    return false;
                }
            }
        }

        //base64编码的文本 转为    图片     
        public static Bitmap Base64StringToImage(string str)
        {
            try
            {
                //FileStream ifs = new FileStream(txtFileName, FileMode.Open, FileAccess.Read);
                //StreamReader sr = new StreamReader(ifs);

                //String inputStr = sr.ReadToEnd();
                byte[] arr = Convert.FromBase64String(str);
                MemoryStream ms = new MemoryStream(arr);
                Bitmap bmp = new Bitmap(ms);

                //bmp.Save(txtFileName + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                ////bmp.Save(txtFileName + ".bmp", ImageFormat.Bmp);     
                ////bmp.Save(txtFileName + ".gif", ImageFormat.Gif);     
                ////bmp.Save(txtFileName + ".png", ImageFormat.Png);     
                //ms.Close();
                //sr.Close();
                //ifs.Close();
                //this.pictureBox1.Image = bmp;
                return bmp;
                //printDocument1.PrintController = new StandardPrintController();
                //printDocument1.DefaultPageSettings.PrinterSettings.
                //MessageBox.Show("转换成功！");
            }
            catch (Exception ex)
            {
                return null;
                //MessageBox.Show("Base64StringToImage 转换失败/nException：" + ex.Message);
            }
        }

        public static DataTable ToDataTable<T>(IEnumerable<T> collection)
        {
            var props = typeof(T).GetProperties();
            var dt = new DataTable();
            foreach(PropertyInfo item in props)
            {
                if (item.PropertyType.Equals(typeof(Nullable<int>)))
                {
                    dt.Columns.Add(new DataColumn(item.Name, typeof(int)));
                }else if (item.PropertyType.Equals(typeof(Nullable<decimal>)))
                {
                    dt.Columns.Add(new DataColumn(item.Name, typeof(decimal)));
                }
                else if (item.PropertyType.Equals(typeof(Nullable<DateTime>)))
                {
                    dt.Columns.Add(new DataColumn(item.Name, typeof(DateTime)));
                }
                else if (item.PropertyType.Equals(typeof(Nullable<bool>)))
                {
                    dt.Columns.Add(new DataColumn(item.Name, typeof(bool)));
                }
                else
                {
                    dt.Columns.Add(new DataColumn(item.Name, item.PropertyType));
                }
            }
           // dt.Columns.AddRange(props.Select(p => new DataColumn(p.Name, p.PropertyType.ToValueType())).ToArray());
            if (collection.Count() > 0)
            {
                for (int i = 0; i < collection.Count(); i++)
                {
                    ArrayList tempList = new ArrayList();
                    foreach (PropertyInfo pi in props)
                    {
                        object obj = pi.GetValue(collection.ElementAt(i), null);
                        tempList.Add(obj);
                    }
                    object[] array = tempList.ToArray();
                    dt.LoadDataRow(array, true);
                }
            }
            return dt;
        }

        /// <summary>
        /// 产生验证码
        /// </summary>
        /// <returns>验证码</returns>
        public static string CreateAuthStr(int len)
        {
            int number;
            StringBuilder checkCode = new StringBuilder();
            Random random = new Random();
            for (int i = 0; i < len; i++)
            {
                number = random.Next();

                if (number % 2 == 0)
                {
                    checkCode.Append((char)('0' + (char)(number % 10)));
                }
                else
                {
                    //checkCode.Append((char)('A' + (char)(number % 26)));
                    checkCode.Append((char)('0' + (char)(number % 10)));
                }
            }
            return checkCode.ToString();
        }

        public static void ExportExcel(DataTable dt)
        {
            HttpContext curContext = HttpContext.Current;
            //设置编码及附件格式
            curContext.Response.ContentType = "application/vnd.ms-excel";
            curContext.Response.ContentEncoding = Encoding.UTF8;
            curContext.Response.Charset = "";
            string fullName = HttpUtility.UrlEncode("FileName.xls", Encoding.UTF8);
            curContext.Response.AppendHeader("Content-Disposition",
                "attachment;filename=" + HttpUtility.UrlEncode(fullName, Encoding.UTF8));  //attachment后面是分号

            byte[] data = TableToExcel(dt, fullName).GetBuffer();
            curContext.Response.BinaryWrite(TableToExcel(dt, fullName).GetBuffer());
            curContext.Response.End();
        }

    public static MemoryStream TableToExcel(DataTable dt, string file)
    {
        //创建workbook
        IWorkbook workbook;
        string fileExt = Path.GetExtension(file).ToLower();
        if (fileExt == ".xlsx")
            workbook = new XSSFWorkbook();
        else if (fileExt == ".xls")
            workbook = new HSSFWorkbook();
        else
            workbook = null;
        //创建sheet
        ISheet sheet = workbook.CreateSheet("Sheet1");

        //表头
        IRow headrow = sheet.CreateRow(0);
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            ICell headcell = headrow.CreateCell(i);
            headcell.SetCellValue(dt.Columns[i].ColumnName);
        }
        //表内数据
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            IRow row = sheet.CreateRow(i + 1);
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                ICell cell = row.CreateCell(j);
                cell.SetCellValue(dt.Rows[i][j].ToString());
            }
        }

        //转化为字节数组
        MemoryStream ms = new MemoryStream();
        workbook.Write(ms);
        ms.Flush();
        ms.Position = 0;
        return ms;
    }

    }
}
